package com.sc.outpatientsys.controller;

import com.sc.outpatientsys.service.ex.*;
import com.sc.outpatientsys.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

public class BaseController {
    public static final int OK = 200;

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UserNameHasExistException){
            result.setState(4000);
            result.setMessage("用户名已被占用");
        }
        else if(e instanceof NotFindException){
            result.setState(4004);
            result.setMessage("未找到");
        }
        else if(e instanceof InsertException){
            result.setState(5000);
            result.setMessage("添加用户时出现意料之外的错误");
        }
        else if(e instanceof PasswordNotMacthException){
            result.setState(5001);
            result.setMessage("用户名密码错误");
        }
        else if(e instanceof UpdateException){
            result.setState(5002);
            result.setMessage("修改时出现了意料外的错误");
        }
        else if(e instanceof DeleteException){
            result.setState(5003);
            result.setMessage("删除时出现了意料外的错误");
        }
        return result;
    }

    protected final String getUserNameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
    protected final Integer getIdFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("id").toString());
    }
}
